#!/usr/bin/env bash

set -o pipefail

# NOTE: any relevant changes to var/ must be accompanied by an
# increment to the revision.

revision=3

top="$(pwd)" || exit $?

usage()
{
    echo 'Usage: dev/configure-sampledata [--setup | --clean | --revision]'
}

if test "$#" -ne 1; then
    usage 1>&2; exit 1
fi

rm_symlinks()
{
    for p in "$@"; do
        # test -e is false for dangling symlinks.
        if test -h "$p" -o -e "$p"; then rm "$p" || exit $?; fi
    done
}

clean()
(
    cd test/sampledata || exit $?
    if test -e var; then rm -r var || exit $?; fi
    # Remove legacy content (before everything moved to var/).
    rm_symlinks abs-symlink b c etc
)

case "$1" in
    --setup)
        (
            clean
            mkdir -p test/sampledata/var/rev || exit $?
            cd test/sampledata/var || exit $?
            ln -sf a b || exit $?
            ln -sf b c || exit $?
            ln -sf "$(pwd)/abs-symlink-target" abs-symlink || exit $?
            mkfifo fifo
            mkdir -p cmd doc lib/bup || exit $?
            cp -pP "$top"/lib/bup/*.py lib/bup/ || exit $?
            cp -pP "$top"/Documentation/*.md doc/ || exit $?
            cp -pP "$top"/lib/bup/*.py lib/bup || exit $?
            mkdir path-zoo || exit $?
            if test "$BUP_TEST_RANDOMIZED_SAMPLEDATA_PATHS"; then
                "$top"/dev/make-random-paths 3000 path-zoo || exit $?
            fi
            # The "v" ensures that if "configure-sampledata
            # --revision" and/or the setup above fails somehow,
            # callers like make will be looking for a file that won't
            # exist.
            touch rev/v$revision || exit $?
        ) || exit $?
        ;;
    --clean)
        clean
        ;;
    --revision)
        echo "$revision" || exit $?
        ;;
    *)
        usage 1>&2; exit 1
        ;;
esac
